package com.pjc.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import com.pjc.db.MySqlConn;
import com.pjc.db.RedisDB;
import com.pjc.model.AccessSrv;
import com.pjc.utils.MsgPackUtils;
import com.pjc.utils.MysqlUtils;
import com.pjc.utils.MysqlUtils.RowHandler;

/**
 * 消息服务类
 * 
 * @author 王畅
 * @since 2015年6月21日
 */
public class AccessSrvDao {

	private static RowHandler<AccessSrv> AccessSrvRowHandler = new RowHandler<AccessSrv>() {
		public AccessSrv execute(ResultSet row) throws SQLException {
			AccessSrv srv = new AccessSrv();
			srv.setId(row.getInt("id"));
			srv.setHost(row.getString("host"));
			srv.setStatus(row.getInt("status"));
			srv.setThriftPort(row.getInt("port"));
			srv.setTimeout(row.getInt("timeout"));
			return srv;
		}
	};

	/**
	 * 获取消息服务器列表
	 * 
	 * @param cnn
	 * @return
	 * @throws Exception
	 */
	public static List<AccessSrv> getAccessSrvList(Connection cnn) throws Exception {
		String sql = "select * from access_srv where status = ?";
		return MysqlUtils.queryList(cnn, AccessSrvRowHandler, sql, new Object[] { Integer.valueOf(0) });
	}

	/**
	 * REDIS中获取消息服务配置
	 * 
	 * @param srvKey
	 * @param srvId
	 * @return
	 * @throws Exception
	 */
	public static AccessSrv getAccessScr(String srvKey, int srvId) throws Exception {
		byte[] key = (srvKey + srvId).getBytes();
		byte[] val = RedisDB.getInstance().get(key);
		if ((val == null) || (val.length == 0)) {
			AccessSrv srv = getAccessFromDb(srvId);
			if (srv != null) {
				RedisDB.getInstance().setData(key, MsgPackUtils.getMsgPack().write(srv));
			}
			return srv;
		}
		return (AccessSrv) MsgPackUtils.getMsgPack().read(val, AccessSrv.class);
	}

	/**
	 * MYSQL中获取消息服务配置
	 * 
	 * @param srvId
	 * @return
	 * @throws Exception
	 */
	public static AccessSrv getAccessFromDb(int srvId) throws Exception {
		String sql = "select * from access_srv where id = ? and status =?";
		return MysqlUtils.queryObj(MySqlConn.getInstance().getConn(), AccessSrvRowHandler, sql, new Object[] { Integer.valueOf(srvId), Integer.valueOf(0) });
	}
}